package moe.service;

import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import moe.config.Configuration;
import moe.entity.Post;
import moe.server.HttpSession;
import moe.server.ImageCache;
import moe.util.JSONBuilder;
import moe.util.Paging;

import org.apache.http.HttpHeaders;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.entity.StringEntity;
import org.apache.http.protocol.ExecutionContext;
import org.apache.http.protocol.HttpContext;

public abstract class AbstractHandler {

	protected void sendJsonResponse(HttpResponse response, String json) {
		StringEntity entity = null;
		try {
			entity = new StringEntity(json, "application/json", "UTF-8");
		} catch (UnsupportedEncodingException e) {
			response.setStatusCode(HttpStatus.SC_INTERNAL_SERVER_ERROR);
			return;
		}
		response.setStatusCode(HttpStatus.SC_OK);
		response.addHeader(HttpHeaders.CACHE_CONTROL, "private, max-age=3600");
		response.setEntity(entity);
	}

	protected Paging createPage(Map<String, String[]> query) {
		Paging paging = new Paging(Configuration.getPageSize());
		if (query.containsKey("page")) {
			paging.setPageNumber(Integer.valueOf(query.get("page")[0]));
		}
		return paging;
	}

	protected String getCallback(Map<String, String[]> query) {
		String callback = null;
		if (query.containsKey("callback")) {
			callback = query.get("callback")[0];
		}
		return callback;
	}

	protected void saveToSession(HttpContext context, Map<String, String[]> query, List<Post> posts) {
		Object object = context.getAttribute(HttpSession.SESSION_CONTEXT);
		if (object == null) {
			return;
		}
		HttpSession session = (HttpSession) object;
		object = session.getAttribute(ImageCache.CACHE_CONTEXT);
		if (object == null) {
			return;
		}
		ImageCache cache = (ImageCache) object;
		cache.setQuery(query);
		cache.setPostList(posts);
	}

	protected JSONBuilder bindPaging(JSONBuilder builder, Paging paging) {
		builder.add("page", new HashMap<String, Object>(), true).add("size", paging.getPageSize())
				.add("current", paging.getPageNumber()).add("total", paging.getPageTotal())
				.add("hasNext", paging.hasNext()).add("hasPrev", paging.hasPre())
				.add("posts_total", paging.getItemTotal()).end();
		return builder;
	}

	protected HttpResponse getHttpResponse(HttpContext context) {
		return (HttpResponse) context.getAttribute(ExecutionContext.HTTP_RESPONSE);
	}
}
